import { getOpt } from "../tools.js";

import SelectWidget from './SelectWidget.js';
// globally assign select2 fn to $ element
import 'select2';
import 'select2/dist/js/i18n/fr';

/*
 * Monkeypatch select2 pour éviter un freeze du scroll endi#2342
 *
 * source: https://github.com/select2/select2/issues/3125#issuecomment-337959828
 * On devrait pouvoir retirer ça quand ça sera corrigé upstream…
 */
$.fn.select2.amd.require(["select2/dropdown/attachBody", "select2/utils"], (AttachBody, Utils) => {
    AttachBody.prototype._attachPositioningHandler = function (decorated, container) {
        var self = this;
        var scrollEvent = "scroll.select2." + container.id;
        var resizeEvent = "resize.select2." + container.id;
        var orientationEvent = "orientationchange.select2." + container.id;
        var $watchers = this.$container.parents().filter(Utils.hasScroll);
        $watchers.each(function () {
            $(this).data("select2-scroll-position", {
                x: $(this).scrollLeft(),
                y: $(this).scrollTop()
            });
        });
        $watchers.on(scrollEvent, function (ev) {
            var position = $(this).data("select2-scroll-position");
            $(self).scrollTop(position.y); // patch: this => self
        });
        $(window).on(scrollEvent + " " + resizeEvent + " " + orientationEvent,
            function (e) {
                self._positionDropdown();
                self._resizeDropdown();
            }
        );
    };
});


const Select2Widget = SelectWidget.extend({
    /*
     * A select2 widget
     *
     * Share the API of SelectWidget
     */
    getSelect2Params: function() {
        let params = {
            width: '100%',
            placeholder: getOpt(this, 'placeholder', undefined),
            allowClear: ! getOpt(this, 'required', false),
            language: 'fr',
        };
        // For clearable multi-select placeholders, a default placeholder is required.
        if (params.allowClear && (params.placeholder === undefined)) {
            params.placeholder = '';
        }
        return params;
    },
    onBeforeAttach: function() {
        if (!getOpt(this, 'field_id', false)) {
            console.error("Select2 '" + getOpt(this, 'field_name', "inconnu") + "' : aucun field_id n'est fourni pour le widget, la navigation au clavier ne fonctionnera pas")
        }
        const selectUI = this.getUI("select");
        selectUI.select2(this.getSelect2Params());
        selectUI.on('select2:open', (e) => {
            const selectId = e.target.id
            $(".select2-search__field[aria-controls='select2-" + selectId + "-results']").each(
                function (key, value) {
                    value.focus();
                }
            )
        })
        const this_ = this;
        selectUI.on('select2:close', function(event) {
            let selectId = this_.getTagId();
            $('.select2-selection[aria-labelledby="select2-' + selectId + '-container"]').focus()
        });
    },
    onBeforeDetach: function() {
       this.getUI('select').select2('destroy');
    },
    initializePlaceHolder: function(placeholder, options) {
        /* Empty <option> is required in DOM, see
         * https://select2.org/placeholders#single-select-placeholders
         */
        let emptyOption = {[this.id_key]: '', [this.label_key]: ''};
        if (!_.findWhere(options, emptyOption)){
            options.unshift(emptyOption);
        }
    },
});
export default Select2Widget;
